<template>
  <div class="my-container d-flex flex-column p-3">
    <div class="shadow rounded-lg d-flex flex-column">
      <div class="d-flex flex-column">
        <div class="p-3">
          <div class="d-flex flex-row flex-wrap ">
            <div class="col-1 col-center">
              <el-button type="success" @click="returnUrl()">返回</el-button>
            </div>
            <div class="col-13 col-center">
              <span class="font-weight-bold">设备名称：</span>
              <span>{{ tabList.deviceName }}</span>
            </div>
            <div class="col-13 col-center">
              <span class="font-weight-bold">设备编码：</span>
              <span>{{ tabList.deviceCode }}</span>
            </div>
            <div class="col-13 col-center">
              <span class="font-weight-bold">设备描述：</span>
              <span>{{ tabList.deviceDes }}</span>
            </div>
            <div class="col-13 col-center">
              <span class="font-weight-bold">创建时间：</span>
              <span>{{ tabList.createTime }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- <div class="d-flex mb-3">
			<el-button v-for="(item, index) in tab" :key="index" :type="tabIndex == index ? 'primary' : 'text'"
				@click="tabIndex = index">{{ item }}</el-button>
		</div> -->
    <div class="col shadow rounded-lg mt-3 d-flex flex-column">
      <el-tabs v-model="tabIndex" type="card" @tab-click="handleClick">
        <el-tab-pane label="设备模型参数" name="0"></el-tab-pane>
        <el-tab-pane label="配置设备基础信息" name="1"></el-tab-pane>
        <el-tab-pane label="设备绑定" name="2"></el-tab-pane>
      </el-tabs>

      <div class="p-3 d-flex flex-column col over-auto" v-if="tabIndex == '0'">
        <el-table height="100%" border :data="deviceModelTable" v-loading="tableLoading" ref="tableRef1">
          <el-table-column type="index" label="序号" width="80" align="center"/>
          <el-table-column prop="parameterName" label="参数名称" align="center"/>
          <el-table-column prop="parameterCode" label="参数代码" align="center"/>
          <el-table-column prop="parameterValue" label="参数值" align="center">
          </el-table-column>
        </el-table>
        <pagination class="pagination" :total="count" :page.sync="deviceModel.pageIndex"
                    :limit.sync="deviceModel.pageSize" @pagination="pagination"/>
      </div>

      <div class="p-3 d-flex flex-column col over-auto" v-if="tabIndex == '1'">
        <div class="   col over-auto">
          <el-table height="100%" border :data="deviceInfoTable" v-loading="tableLoading" ref="tableRef2">
            <el-table-column type="index" label="序号" align="center" width="300"></el-table-column>
            <el-table-column prop="label" label="配置对象" align="center">
            </el-table-column>
            <el-table-column prop="roleName" label="配置内容" align="center">
              <template slot-scope="scope">
                <span v-if="scope.row.type == 1">
                  <el-input disabled size="mini" v-model="isForceData.deviceOfRegionSysName"
                            style="width: 200px; margin-right: 10px;" placeholder="请选择"/>
                  <el-button type="primary" size="mini" @click="handleTree">
                    选择</el-button>
                </span>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="d-flex mt-3 justify-content-center">
          <el-button type="primary" @click="handleSaveInfo">保存</el-button>
        </div>
      </div>

      <div class="p-3 d-flex flex-column col over-auto" v-if="tabIndex == '2'">
        <div>
          <el-form>
            <el-form-item>
              <el-button v-if="tabList.modelType == '配电箱类型'" type="primary" @click="handleQuery('')">查找设备</el-button>
              <!--              <el-button v-else type="primary" @click="handleQuery()">查找设备</el-button>-->
            </el-form-item>
          </el-form>
        </div>
        <template v-if="tabList.modelType == '配电箱类型'">
          <el-table height="320px" border v-loading="tableLoading" :data="distributionBoxList">
            <el-table-column type="index" label="序号" width="80" align="center"/>
            <el-table-column prop="deviceName" label="设备名称" align="center"/>
            <el-table-column prop="deviceCode" label="设备编码" align="center"/>
            <el-table-column prop="deviceDes" label="设备描述" align="center">
              <template slot-scope="scope">
                {{ scope.row.deviceDes }}
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center">
              <template slot-scope="scope">
                <el-button size="mini" @click="removeDx(scope.row,'1')" type="warning">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <pagination class="pagination" :total="boundCount" :page.sync="boundModel.pageIndex"
                      :limit.sync="boundModel.pageSize" @pagination="boundPagination"/>
        </template>
        <template v-else>
          <el-table height="320px" border v-loading="tableLoading" :data="distributionBoxList">
            <el-table-column type="index" label="序号" width="80" align="center"/>
            <el-table-column label="上级设备" align="center">
              <template slot-scope="scope">
                <span class="d-flex">
                  <el-input disabled v-model="scope.row.bindUpDeviceName"
                            style="margin-right: 10px;" placeholder="请选择"/>
                  <el-button type="primary" size="medium" @click="handleQuery('up')">选择</el-button>
                </span>
              </template>
            </el-table-column>
            <el-table-column label="下级设备" align="center">
              <template slot-scope="scope">
                <span v-if="scope.row" class="d-flex">
                  <el-input disabled v-model="scope.row.bindDownDeviceName"
                            style="margin-right: 10px;" placeholder="请选择"/>
                  <el-button type="primary" size="medium" @click="handleQuery('down')">选择</el-button>
                </span>
              </template>
            </el-table-column>
          </el-table>
          <div class="d-flex mt-3 justify-content-center" v-if="tabList.modelType != '配电箱类型'">
            <el-button type="primary" @click="handleSaveDx">保存</el-button>
          </div>
        </template>
      </div>
    </div>

    <!-- 区域位置 -->
    <yc-dialog ref="regionDialog" centerTitle="选择" dialogTitle="区域位置">
      <template #content>
        <el-tree ref="tree1" :default-checked-keys="[regionTreeAction.deviceOfRegion]" node-key="zoneCode"
                 :data="regionTreeData" show-checkbox check-strictly :props="defaultProps" check-on-click-node
                 :expand-on-click-node="false" highlight-current @check="deptNodeClick"/>
      </template>
      <template #footer>
        <el-button type="primary" @click="regionTreeSave()">确定</el-button>
        <el-button @click="$refs.regionDialog.dialogVisible = false">取消
        </el-button>
      </template>
    </yc-dialog>

    <!-- 设备查询 -->
    <yc-dialog ref="queryDialog" centerTitle="查找" dialogTitle="查找设备" :show-center="false">
      <template #content>
        <div class="title-container">
          <div class="search-content">
            <el-form :model="searchModel" :inline="true">
              <el-form-item>
                <el-input v-model="searchModel.deviceName" clearable @clear="getQueryPageDevice" placeholder="请输入设备名称"
                          prefix-icon="el-icon-search"/>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="getQueryPageDevice">搜索</el-button>
              </el-form-item>
            </el-form>
          </div>
        </div>
        <el-table height="260px" border :data="deviceBindingList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center"></el-table-column>
          <el-table-column prop="deviceName" label="设备名称" align="center"/>
          <el-table-column prop="deviceCode" label="设备编码" align="center"/>
          <el-table-column prop="deviceDes" label="设备描述" align="center"/>
        </el-table>
        <pagination class="pagination" :total="bindingModelCount" :page.sync="bindingModel.pageIndex"
                    :limit.sync="bindingModel.pageSize" @pagination="bindingPagination"/>
      </template>
      <template #footer>
        <el-button type="primary" @click="handleAdd()">添加</el-button>
      </template>
    </yc-dialog>
  </div>
</template>

<script>
  import ycDialog from "@/components/pageDialog"
  import {
    queryGHDeviceParPage,
    queryOneDevice,
    updateOneDevice,
    queryPdxDevicePage,
    queryPageDevice,
    insertPdxDevice,
    deletePdxDevice,
    queryDxDevice,
    insertDxDevice,
    deleteDxDevice,
    updateDxDevice
  } from "@/api/settingManagement/devicesSetting"
  import { selectZonePage } from "@/api/regionalSettings"

  export default {
    components: {
      ycDialog
    },
    props: {},
    data() {
      return {
        activeName: "first",
        showTag: false,

        tagInput: "",
        tagList: [], //自定义参数标签
        dataForm: {
          parameterName: "",
          parameterZeroValue: "",
          parameterOneValue: ""
        },
        select: "",
        tabIndex: "0",

        tabList: {},
        detailId: "",

        count: 0,
        deviceModel: {
          pageIndex: 1,
          pageSize: 20
        },
        customParams: {
          pageIndex: 1,
          pageSize: 20
        },
        deviceModelTable: [],
        deviceInfoTable: [
          {
            label: "设备区域",
            type: 1
          }
        ],
        isForceData: {
          deviceOfRegionSysName: ""
        },
        isForceShowType: [],

        regionTreeData: [],
        defaultProps: {
          children: "bZoneList",
          label: "zoneName"
        },
        regionTreeAction: {
          deviceOfRegionName: "",
          deviceOfRegion: ""
        },
        customTable: [],
        customTitle: "",
        customsAddType: "",
        customDialogType: "",
        mapString: [],
        parameterOwnerSysCode: "",
        searchModel: {
          userName: ""
        },
        distributionBoxList: [],
        deviceBindingList: [],
        bindingModel: {
          pageIndex: 1,
          pageSize: 20
        },
        boundModel: {
          pageIndex: 1,
          pageSize: 20
        },
        bindingModelCount: 0,
        boundCount: 0,
        selectedDeviceList: [],
        tableLoading: false,
        dxType: ""
      }
    },
    created() {

    },
    mounted() {
      this.deviceCode = this.$route.query.deviceCode
      this.tabList = this.$route.query
      this.queryGHDeviceParPage()
    },
    methods: {
      returnUrl() {
        this.$router.go(-1)
      },
      handleClick(tab, event) {
        switch (tab.name) {
          case "0":
            this.queryGHDeviceParPage()
            break
          case "1":
            this.getQueryOneDevice()
            break
          case "2":
            this.getQueryPdxDevicePage()
            break
          default:
            break
        }
      },

      queryGHDeviceParPage() {
        this.tableLoading = true
        queryGHDeviceParPage({
          deviceCode: this.deviceCode,
          ...this.deviceModel
        }).then(res => {
          if (res.status == 200) {
            this.count = res.object.count
            this.deviceModelTable = res.object.data
          }
          this.tableLoading = false
        })
      },
      async getQueryOneDevice() {
        const res = await queryOneDevice({ deviceCode: this.deviceCode })
        if (res.status == 200) {
          this.isForceData = res.object
          this.regionTreeAction.deviceOfRegion = this.isForceData.deviceOfRegion
        }
      },
      handleTree() {
        this.getZone()
        this.$refs.regionDialog.dialogVisible = true
      },
      deptNodeClick(data) {
        this.$refs.tree1.setCheckedNodes([{
          zoneCode: data.zoneCode,
          zoneName: data.zoneName
        }])
        this.regionTreeAction.deviceOfRegion = data.zoneCode
        this.regionTreeAction.deviceOfRegionName = data.zoneName
      },

      pagination(pageItem) {
        // pageItem.page, pageItem.limit
        this.deviceModel.pageIndex = pageItem.page
        this.deviceModel.pageSize = pageItem.limit
        this.queryGHDeviceParPage()
      },
      regionTreeSave() {
        this.isForceData.deviceOfRegionSysName = this.regionTreeAction.deviceOfRegionName
        this.$refs.regionDialog.dialogVisible = false
      },
      //////////-2
      async getZone() {
        const res = await selectZonePage()
        if (res.status == "200") {
          this.$nextTick(() => {
            this.regionTreeData = res.object
          })
        }
      },
      async handleSaveInfo() {
        const param = {
          deviceCode: this.deviceCode,
          ...this.regionTreeAction
        }
        const res = await updateOneDevice(param)
        if (res.status == "200") {
          this.$message({
            type: "success",
            message: res.message
          })
          this.getQueryOneDevice()
        }
      },
      //--------固化设备-配电箱设备 ---
      handleQuery(type) {
        this.dxType = type
        this.$refs.queryDialog.dialogVisible = true
        this.getQueryPageDevice()
      },

      handleSelectionChange(val) {
        this.selectedDeviceList = val
      },

      async handleAdd(type) {
        if (this.tabList.modelType == "配电箱类型") {
          const res = await insertPdxDevice({
            dxDeviceCode: this.tabList.deviceCode,
            messages: this.selectedDeviceList.map((v) => v.deviceCode).join("&")
          })
          if (res.status == "200") {
            this.$message({
              type: "success",
              message: res.message
            })
            this.$refs.queryDialog.dialogVisible = false
            this.getQueryPdxDevicePage()
          }
        } else {
          if (this.selectedDeviceList.length != 1) {
            this.$message({
              message: "请选择一条数据",
              type: "warning"
            })
            return
          }
          if (this.dxType == "up") {
            this.distributionBoxList[0].bindUpDeviceName = this.selectedDeviceList[0].deviceName
            this.distributionBoxList[0].bindUpDeviceCode = this.selectedDeviceList[0].deviceCode
          } else {
            this.distributionBoxList[0].bindDownDeviceName = this.selectedDeviceList[0].deviceName
            this.distributionBoxList[0].bindDownDeviceCode = this.selectedDeviceList[0].deviceCode
          }
          this.$refs.queryDialog.dialogVisible = false
        }
      },

      async getQueryPageDevice() {
        const res = await queryPageDevice({
          ...this.bindingModel,
          deviceName: this.searchModel.deviceName,
          deviceType: "0"
        })
        if (res.status == "200") {
          this.deviceBindingList = res.object.data
          this.bindingModelCount = res.object.count
        }
      },
      bindingPagination(pageItem) {
        this.bindingModel.pageIndex = pageItem.page
        this.bindingModel.pageSize = pageItem.limit
        this.getQueryPageDevice()
      },


      async getQueryPdxDevicePage() {
        this.tableLoading = true
        if (this.tabList.modelType == "配电箱类型") {
          const res = await queryPdxDevicePage({ dxDeviceCode: this.tabList.deviceCode, ...this.boundModel })
          if (res.status == "200") {
            this.distributionBoxList = res.object.data
            this.boundCount = res.object.count
          }
        } else {
          const res = await queryDxDevice({ deviceCode: this.tabList.deviceCode })
          if (res.status == "200") {
            this.distributionBoxList = res.object ? [res.object] : [{
              bindUpDeviceName: "",
              bindUpDeviceCode: "",
              bindDownDeviceName: "",
              bindDownDeviceCode: ""
            }]
          }
        }

        this.tableLoading = false
      },

      boundPagination(pageItem) {
        this.boundModel.pageIndex = pageItem.page
        this.boundModel.pageSize = pageItem.limit
        this.getQueryPdxDevicePage()
      },

      async handleSaveDx() {
        if (!this.distributionBoxList[0].bindUpDeviceCode) {
          this.$message({
            message: "请选择上级设备",
            type: "warning"
          })
          return
        }
        if (!this.distributionBoxList[0].bindDownDeviceCode) {
          this.$message({
            message: "请选择下级设备",
            type: "warning"
          })
          return
        }
        const param = {
          deviceCode: this.deviceCode,
          bindUpDeviceCode: this.distributionBoxList[0].bindUpDeviceCode,
          bindDownDeviceCode: this.distributionBoxList[0].bindDownDeviceCode
        }
        const res = await updateDxDevice(param)
        if (res.status == "200") {
          this.$message({
            type: "success",
            message: res.message
          })
          this.getQueryPdxDevicePage()
        }
      },

      async removeDx(row, type) {
        const apiUrl = type == "1" ? deletePdxDevice : deleteDxDevice
        const res = await apiUrl({ id: row.id })
        if (res.status == "200") {
          this.$message({
            type: "success",
            message: res.message
          })
          this.getQueryPdxDevicePage()
        }
      }
    }
  }
</script>

<style scoped lang="scss">
  .tab-item {
    width: 20%;
  }

  .pagination {
    display: flex;
    justify-content: flex-end;
  }
</style>
